<template>
  <div class="contribution-mgr">
    <!-- 搜索区域 -->
    <div class="search-area">
      <a-form-model layout="inline">
        <a-form-model-item label="作品名">
          <a-input
            v-model="searchForm.title"
            placeholder="作品名"
            allowClear
            @change="handleSearch"
          />
        </a-form-model-item>
        
        <a-form-model-item label="作者">
          <a-input
            style="width: 120px"
            v-model="searchForm.author"
            placeholder="请输入作者名"
            allowClear
            @change="handleSearch"
          />
        </a-form-model-item>
        
        <a-form-model-item label="项目组">
          <a-select
            v-model="searchForm.project_group_id"
            placeholder="选择项目组"
            :loading="projectGroupLoading"
            show-search
            :filter-option="false"
            :default-active-first-option="false"
            :show-arrow="false"
            :not-found-content="projectGroupLoading ? '加载中...' : '未找到'"
            @search="handleSearchProjectGroup"
            allowClear
            @change="handleSearch"
            style="width: 200px"
          >
            <a-select-option
              v-for="item in projectGroupList"
              :key="item.project_group_id"
              :value="item.project_group_id"
            >
              {{ item.project_group_name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="审核状态">
          <a-select
            v-model="searchForm.approved_status"
            placeholder="审核状态"
            allowClear
            @change="handleSearch"
            style="width: 120px"
          >
            <a-select-option :value="0">待审核</a-select-option>
            <a-select-option :value="1">已审核</a-select-option>
            <a-select-option :value="2">未采用</a-select-option>
            <a-select-option :value="3">未打分</a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="提交日期">
          <a-range-picker
            v-model="dateRange"
            @change="handleDateChange"
            :placeholder="['开始日期', '结束日期']"
          />
        </a-form-model-item>
        
        <a-form-model-item>
          <a-button type="primary" @click="handleSearch">
            查询
          </a-button>
          <a-button style="margin-left: 8px" @click="handleReset">
            重置
          </a-button>
          <a-button type="primary" style="margin-left: 8px;background: #52c41a" v-show="isAdmin || isAudit" @click="handleBatchScore">
            批量打分
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    
    <!-- 表格区域 -->
    <div class="table-area">
      <vxe-table
        ref="xTable"
        :loading="loading"
        :data="tableData"
        :auto-resize="true"
        :height="tableHeight"
        resizable
        show-overflow="tooltip"
      >
        <vxe-column type="checkbox" title="" width="60"></vxe-column>
        <vxe-column field="contribution_id" title="ID" width="60" />
        <vxe-column field="title" title="作品名" min-width="360" show-overflow="tooltip" />
        <vxe-column field="author1_name" title="作者1" width="160">
          <template v-slot="{ row }">
            {{ row.author1_name }} ({{ row.author1_department_name }})
          </template>
        </vxe-column>
        <vxe-column field="author2_name" title="作者2" width="160">
          <template v-slot="{ row }">
            <template v-if="row.author2_name">
              {{ row.author2_name }} ({{ row.author2_department_name }})
            </template>
          </template>
        </vxe-column>
        <vxe-column field="author3_name" title="作者3" width="160">
          <template v-slot="{ row }">
            <template v-if="row.author3_name">
              {{ row.author3_name }} ({{ row.author3_department_name }})
            </template>
          </template>
        </vxe-column>
        <vxe-column field="project_group_name" title="项目组" width="120" />
        <vxe-column field="approved_status" title="审核状态" width="100">
          <template v-slot="{ row }">
            <a-tag :color="getStatusColor(row.approved_status)">
              {{ getStatusText(row.approved_status) }}
            </a-tag>
          </template>
        </vxe-column>
        <vxe-column field="approved_remark" title="审核意见" width="100" />        
        <vxe-column field="approved_person_name" title="审核人" width="100" v-if="isAdmin || isAudit" />
        <vxe-column field="score" title="总分" width="80" />
        <vxe-column field="scoring_person_name" title="打分人" width="100" v-if="isAdmin || isAudit" />
        <vxe-column field="author1_score" title="作者1得分" width="100" />
        <vxe-column field="author2_score" title="作者2得分" width="100" />
        <vxe-column field="author3_score" title="作者3得分" width="100" />
        <!-- <vxe-column field="extra_score" title="额外得分" width="100" />
        <vxe-column field="tiktok_likes" title="抖音点赞数" width="120" />
        <vxe-column field="channels_views" title="视频号播放量" width="120" />
        <vxe-column field="channels_likes" title="视频号点赞数" width="120" /> -->
        <vxe-column field="submission_date" title="提交时间" width="160">
          <template v-slot="{ row }">
            {{ formatDate(row.submission_date) }}
          </template>
        </vxe-column>
        <vxe-column field="platform_submit_date" title="发布时间" width="160">
          <template v-slot="{ row }">
            {{ formatDate(row.platform_submit_date) }}
          </template>
        </vxe-column>
        <!-- <vxe-column field="created_at" title="创建时间" width="160">
          <template v-slot="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </vxe-column> -->
        <vxe-column field="remarks" title="备注" min-width="150" show-overflow="tooltip" />
        <vxe-column title="操作" width="220" fixed="right">
          <template v-slot="{ row }">
            <a-button 
              v-if="(isAdmin || isAudit) && row.approved_status === 0"
              type="link" 
              size="small"
              style="color: #52c41a"
              @click="handleApprove(row)"
            >
              审核
            </a-button>
            <a-button 
              v-if="isAdmin && row.approved_status === 1 && !row.score"
              type="link" 
              size="small"
              style="color: #52c41a"
              @click="handleScore(row)"
            >
              打分
            </a-button>
            <a-button 
              v-if="canDelete(row)"
              type="link" 
              size="small"
              style="color: #ff4d4f"
              @click="handleDelete(row)"
            >
              删除
            </a-button>
            <a-button 
              v-show="row.video_file_path && (isAdmin || isAudit)"
              type="link" 
              size="small"
              style="color: #007BFF"
              @click="handleDownload(row)"
            >
              下载
            </a-button>
          </template>
        </vxe-column>
      </vxe-table>
      
      <!-- 分页 -->
      <!-- <vxe-pager
        :current-page="page.current"
        :page-size="page.size"
        :total="page.total"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
        @page-change="handlePageChange"
      /> -->

      <div class="pagination-container">
        <a-pagination v-model="page.current" :total="page.total" :page-size="page.size"
          :page-size-options="['10', '20', '30', '40']" show-size-changer show-quick-jumper
          :show-total="total => `共 ${total} 条记录`" @change="handlePageChange" @showSizeChange="handleSizeChange" />
      </div>
    </div>

    <!-- 审核弹窗 -->
    <a-modal
      v-model="approvedVisible"
      title="审核"
    >
      <strong>标题</strong>
      <br>
      <a-input
       style="margin:12px 0"
        v-model="approvedTitle"
        placeholder="标题"
      />
      <br>
      <strong>审核意见</strong>
      <br>
      <a-textarea
        style="margin:12px 0"
        v-model="approvedRemark"
        placeholder="请输入审核意见"
        :auto-size="{ minRows: 3, maxRows: 5 }"
      />
      <template slot="footer">
        <a-button key="back"  :loading="loading" @click="submitApprove(approvedRow.contribution_id,2,approvedRemark)">
          不通过
        </a-button>
        <a-button key="submit" type="primary" :loading="loading"  @click="submitApprove(approvedRow.contribution_id,1,approvedRemark)">
          通过
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { 
  apiContributionList, 
  apiContributionDelete,
  apiProjectGroupList,
  apiContributionApprove,
  apiContributionScore,
  apiContributionImportPlatformData
} from '@/api/featch'
import moment from 'moment'

const client = new AWS.S3({
  accessKeyId: 'B0EBM7IA33R7RE9M8BPY',
  secretAccessKey: 'ABb5DiBletAUO1AmcMT6M1wORLtBUh0OZXWZ6zn5',
  endpoint: 'https://hangzhou7.zos.ctyun.cn',
  sslEnabled: true,
  s3ForcePathStyle: true,
})

const Bucket = 'jyrmggcc'

export default {
  name: 'ContributionMgr',
  data() {
    return {
      moment,  // 添加到data中
      // 搜索表单
      searchForm: {
        title: '',
        author: '',
        project_group_id: undefined,
        approved_status: undefined,
        start_date: undefined,
        end_date: undefined
      },
      
      // 日期范围
      dateRange: [],
      
      // 表格数据
      tableData: [],
      loading: false,
      tableHeight: null,
      
      // 分页信息
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      
      // 项目组列表
      projectGroupList: [],
      projectGroupLoading: false,
      
      // 打分表单
      scoreForm: {
        score: undefined,
        platform_submit_date: null
      },
      userInfo: {},
      // 当前用户ID
      currentUserId: null,

      approvedVisible: false,
      approvedRow: {},
      approvedRemark: null,
      approvedTitle: null
    }
  },
  computed: {
    isAdmin() {
      return this.userInfo.role === '系统管理员'
    },
    isAudit() {
      return this.userInfo.role === '审核员'
    }
  },
  mounted() {
    this.searchForm.approved_status = this.$route.params.approved_status
    this.initTableHeight()
    this.getTableData()
    this.handleSearchProjectGroup()
    this.checkUserRole()
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.initTableHeight)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.initTableHeight)
  },
  methods: {
    /**
     * @description 格式化日期
     */
    formatDate(date) {
      if (!date) return ''
      return this.moment(date).format('YYYY-MM-DD HH:mm:ss')
    },

    /**
     * @description 获取状态文字
     */
    getStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '已审核',
        2: '未采用'
      }
      return statusMap[status] || '未知'
    },

    /**
     * @description 获取状颜色
     */
    getStatusColor(status) {
      const colorMap = {
        0: 'orange',
        1: 'green',
        2: 'red'
      }
      return colorMap[status] || 'default'
    },

    /**
     * @description 处理日期变化
     */
    handleDateChange(dates) {
      if (dates && dates.length === 2) {
        this.searchForm.start_date = dates[0].format('YYYY-MM-DD')
        this.searchForm.end_date = dates[1].format('YYYY-MM-DD')
      } else {
        this.searchForm.start_date = undefined
        this.searchForm.end_date = undefined
      }
      this.handleSearch()
    },

    /**
     * @description 初始化表格高度
     */
    initTableHeight() {
      const clientHeight = document.documentElement.clientHeight
      this.tableHeight = clientHeight - 64 - 48 - 132 - 44
    },
    
    /**
     * @description 获取表格数据
     */
    async getTableData() {
      this.loading = true
      try {
        const params = {
          page: this.page.current,
          page_size: this.page.size,
          title: this.searchForm.title || undefined,
          author: this.searchForm.author || undefined,
          project_group_id: this.searchForm.project_group_id || undefined,
          approved_status: this.searchForm.approved_status === 3 ? 1 : this.searchForm.approved_status,
          is_scored: this.searchForm.approved_status === 3 ? 0 : null,
          start_date: this.searchForm.start_date,
          end_date: this.searchForm.end_date
        }
        const res = await apiContributionList(params)
        if (res.code === 200) {
          this.tableData = res.data.list || []
          this.page.total = res.data.pagination.total || 0
          
          // 如果当前页没有数据且不是第一页，则跳转到上一页
          if (this.tableData.length === 0 && this.page.current > 1) {
            this.page.current--
            this.getTableData()
          }
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        this.$message.error(err.toString())
      }
      this.loading = false
    },
    
    /**
     * @description 搜索项目组
     */
    async handleSearchProjectGroup(value) {
      this.projectGroupLoading = true
      try {
        const res = await apiProjectGroupList({
          project_group_name: value || undefined
        })
        if (res.code === 200) {
          this.projectGroupList = res.data
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        this.$message.error(err.toString())
      }
      this.projectGroupLoading = false
    },
    
    /**
     * @description 处理搜索
     */
    handleSearch() {
      this.page.current = 1
      this.getTableData()
    },
    
    /**
     * @description 重置搜索
     */
    handleReset() {
      this.searchForm = {
        title: '',
        author: '',
        project_group_id: undefined,
        approved_status: undefined,
        start_date: undefined,
        end_date: undefined
      }
      this.dateRange = []
      this.handleSearch()
    },
    
    /**
     * @description 处理分页变化
     */
    handlePageChange(page) {
      this.page.current = page
      this.getTableData()
    },
    /**
     * @description 每页条数改变
     */
    handleSizeChange(current, size) {
      this.page.current = 1
      this.page.size = size
      this.getTableData()
    },
    
    /**
     * @description 处理编辑
     */
    handleEdit(row) {
      // TODO: 实现编辑功能
      console.log('编辑', row)
    },
    
    /**
     * @description 处理删除
     */
    handleDelete(row) {
      this.$confirm({
        title: '确认删除',
        content: '确定要删除这条投稿记录吗？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: async () => {
          try {
            const res = await apiContributionDelete({
              contribution_id: row.contribution_id
            })
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.getTableData()
            } else {
              this.$message.error(res.message)
              return Promise.reject()
            }
          } catch (err) {
            this.$message.error(err.toString())
            return Promise.reject()
          }
        }
      })
    },

    /**
     * @description 处理审核
     */
    handleApprove(row) {
      this.approvedRow = row
      this.approvedVisible = true
      this.approvedTitle = row.title
    },

    /**
     * @description 提交审核
     */
    async submitApprove(contribution_id, approved_status,approved_remark) {
      if(approved_status === 2 && !approved_remark) {
        this.$message.info('请输入审核意见')
        return
      }
      try {
        const res = await apiContributionApprove({
          contribution_id,
          approved_status,
          approved_remark,
          title: this.approvedTitle ? this.approvedTitle : this.approvedRow.title
        })
        if (res.code === 200) {
          this.$message.success(approved_status === 1 ? '审核通过' : '已设为未采用')
          this.getTableData()
          this.approvedVisible = false
          this.approvedRemark = null
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        this.$message.error(err.toString())
      }
    },

/**
 * @description 处理打分（新增发布日期选择）
 */
handleScore(row) {
  // 重置表单数据（避免上次残留值）
  this.scoreForm = {
    score: undefined,
    platform_submit_date: undefined // 发布日期，非必选
  };

  this.$confirm({
    title: '投稿打分',
    content: h => (
      <div>
        <p>请输入分数：</p>
        <a-input-number 
          v-model={this.scoreForm.score}
          min={0}
          max={100}
          precision={0}
          style="width: 100%; margin-bottom: 16px;"
        />
        <p>发布日期（非必选）：</p>
        <a-date-picker 
          v-model={this.scoreForm.platform_submit_date}
          format="YYYY/MM/DD" // 与后端要求的格式一致
          style="width: 100%"
          placeholder="请选择发布日期"
        />
      </div>
    ),
    okText: '确定',
    cancelText: '取消',
    width: 400,
    onOk: async () => {
      // 验证分数必填
      if (this.scoreForm.score === undefined && this.scoreForm.score !== 0) {
        this.$message.warning('请输入分数');
        return Promise.reject();
      }

      try {
        // 1. 先执行打分操作
        const scoreRes = await apiContributionScore({
          contribution_id: row.contribution_id,
          score: this.scoreForm.score
        });

        if (scoreRes.code !== 200) {
          this.$message.error(scoreRes.message);
          return Promise.reject();
        }

        // 2. 如果填写了发布日期，执行导入平台数据操作
        if (this.scoreForm.platform_submit_date) {
          // 转换日期格式为字符串（YYYY/MM/DD）
          const dateStr = this.scoreForm.platform_submit_date.format('YYYY/MM/DD');
          const platformRes = await apiContributionImportPlatformData({
            contribution_id: row.contribution_id,
            platform_submit_date: dateStr
          });

          if (platformRes.code !== 200) {
            this.$message.warning(`打分成功，但发布日期设置失败：${platformRes.message}`);
            // 此处不阻断流程，因为打分已成功
          }
        }

        // 3. 操作成功，刷新表格
        this.$message.success('打分成功');
        this.getTableData();
        return Promise.resolve();
      } catch (err) {
        this.$message.error(err.toString());
        return Promise.reject();
      }
    }
  });
},
    /**
     * @description 检查用户角色
     */
    checkUserRole() {
      // 获取用户信息
      const personInfo = window.sessionStorage.getItem('person_info')
      if (personInfo) {
        this.userInfo = JSON.parse(personInfo)
        this.currentUserId = this.userInfo.person_id
      }
    },

    /**
     * @description 检查是否可以删除
     */
    canDelete(row) {
      if (this.isAdmin) return true
      return [row.author1, row.author2, row.author3].includes(this.currentUserId)
    },
    /**
     * @description 下载
     */
    handleDownload(row) {
      if(row.video_file_path){
        window.open(`https://hangzhou7.zos.ctyun.cn/jyrmggcc/${row.video_file_path}`, "_blank")
        return
        const params = {
          Bucket,
          Key: row.video_file_path
        }
        client.getObject(params,(err,data) => {
          if (err) {
            console.log(err, err.stack)
          } // an error occurred
          else{ 
            console.log(data)
          } // successful response
        })
      } else {
        this.$message.error('文件不存在')
      }
    },
    /**
     * @description 批量打分
     */
    handleBatchScore() {
      const list =  this.$refs.xTable.getCheckboxRecords()
      console.log(list)
      this.$confirm({
        title: '批量 投稿打分',
        content: h => (
          <div>
            <p>请输入分数：</p>
            <a-input-number 
              v-model={this.scoreForm.score}
              min={0}
              max={100}
              precision={0}
              style="width: 100%"
            />
          </div>
        ),
        okText: '确定',
        cancelText: '取消',
        width: 400,
        onOk: () => {
          if (!this.scoreForm.score && this.scoreForm.score !== 0) {
            this.$message.warning('请输入分数')
            return Promise.reject()
          }
          try {
            const PromiseList = []
            list.map(item => {
              PromiseList.push(apiContributionScore({
                contribution_id: item.contribution_id,
                score: this.scoreForm.score
              }))
            })

            Promise.all(PromiseList)
              .then(resultList => {
                let successCount = 0
                let failCount = 0
                resultList.map(result => {
                  if(result.code === 200) {
                    // 成功
                    ++successCount
                  } else {
                    // 失败
                    ++failCount
                  }
                })
                this.$notification.open({
                  message: '批量打分结果',
                  description:
                    `批量打分结果 成功【${successCount}】条 失败【${failCount}】条`,
                  duration: 0,
                })
                this.getTableData()
                this.scoreForm.score = null
              })
          } catch (err) {
            this.$message.error(err.toString())
            return Promise.reject()
          }
        }
      })
    
    }
  }
}
</script>

<style lang="less" scoped>
.contribution-mgr {
  height: 100%;
  
  .search-area {
    padding: 24px 24px 16px 24px;
    background: #fff;
    border-radius: 4px;
  }
  
  .table-area {
    background: #fff;
    padding: 0 24px;
    border-radius: 4px;
    .pagination-container {
      margin-top: 16px;
      text-align: right;
    }
  }
}
</style>
